package com.example.sherlockzhong.plush_v2.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.widget.ImageView;

public class ImageUtil {

    /**
     * create by DosonLeungs
     *
     * @param v:the             Activity which contains target ImageView
     * @param imageViewID:the   ID of target ImageView
     * @param resID:the         ID of the image resource
     * @param windowWidth:the   width of the window
     * @param shareOfWindow:the ratio that the target ImageView on its window
     * @param aspect_ratio:the  length-width ratio
     */

    public static void scaleImage(View v, int imageViewID, int resID, int windowWidth, double shareOfWindow, double aspect_ratio) {
        int width, height;
        float widthscale = 1;
        float heightscale = 1;
        Matrix matrix = new Matrix();
        int marginLeftRight = 20;
        int iconWidth = (int) ((double) (windowWidth - 2 * marginLeftRight) * shareOfWindow);

        Bitmap bitmap = BitmapFactory.decodeResource(v.getResources(), resID);
        ImageView imageView = (ImageView) v.findViewById(imageViewID);
        width = bitmap.getWidth();
        height = bitmap.getHeight();
        widthscale = (float) iconWidth / (width);
        heightscale = (float) ((double) widthscale * aspect_ratio);
        imageView.setImageBitmap(BitmapFactory.decodeResource(v.getResources(), resID));
        matrix.reset();
        matrix.setScale(widthscale, heightscale);
        BitmapDrawable tmp = (BitmapDrawable) imageView.getDrawable();
        if (!tmp.getBitmap().isRecycled()) {
            tmp.getBitmap().recycle();
        }
        Bitmap bitmap2 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        imageView.setImageBitmap(bitmap2);
    }
}
